package com.mjk.manager.magicapi.conf.interceptor;


import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.tools.encrypt.MD5Util;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.util.StrUtils;
import com.mjk.manager.amis.core.model.PlatUser;
import com.mjk.manager.magicapi.core.core.context.MagicUser;
import com.mjk.manager.magicapi.core.core.exception.MagicLoginException;
import com.mjk.manager.magicapi.core.core.interceptor.Authorization;
import com.mjk.manager.magicapi.core.core.interceptor.AuthorizationInterceptor;
import com.mjk.manager.magicapi.core.core.model.MagicEntity;
import com.mjk.manager.magicapi.core.core.servlet.MagicHttpServletRequest;
import com.mjk.manager.magicapi.core.core.servlet.MagicRequestContextHolder;
import com.mjk.manager.usercenter.sclogin.event.LoginEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自定义UI界面鉴权
 * https://ssssssss.org/magic-api/pages/security/operation/
 *
 * @see AuthorizationInterceptor
 */
public class CustomUIAuthorizationInterceptor implements AuthorizationInterceptor {

	@Autowired
	public MagicRequestContextHolder magicRequestContextHolder;
	private final boolean requireLogin;

	private Map<String,MagicUser> userToken = new ConcurrentHashMap<>();

	@Autowired
	private BeeDBService beeDBService;

	public CustomUIAuthorizationInterceptor() {
		requireLogin = true;
	}

	@EventListener(condition = "#event.type == 'sclogin'")
	public void onGroupEvent(LoginEvent event) {
		try {
			magicRequestContextHolder.setCurrentUser(new MagicUser(event.getUserName(), event.getUserName(), event.getToken()));
		} catch (Exception e) {
			BizLogger.error(e);
		}
	}
	@Override
	public boolean requireLogin() {
		return requireLogin;
	}

	@Override
	public MagicUser getUserByToken(String token) throws MagicLoginException {
		if(userToken.containsKey(token)){
			return userToken.get(token);
		}
		if(StpUtil.isLogin()) {
			BeeQueryWrapper wrapper = new BeeQueryWrapper(PlatUser.class);
			wrapper.eq(PlatUser::getId, StpUtil.getLoginId());
			PlatUser sUser = (PlatUser)beeDBService.findOneByWrapper(wrapper);
			if(sUser!=null){
				return new MagicUser(sUser.getId()+"",sUser.getLOGIN_NAME(),StpUtil.getTokenValue());
			}
		}
		throw new MagicLoginException("token无效");
	}

	@Override
	public MagicUser login(String username, String password) throws MagicLoginException {
			BeeQueryWrapper wrapper = new BeeQueryWrapper(PlatUser.class);
			wrapper.eq(PlatUser::getLOGIN_NAME, username);
			PlatUser sUser = (PlatUser)beeDBService.findOneByWrapper(wrapper);
			if(sUser!=null ){
				password = MD5Util.lowMd5(sUser.getLOGIN_NAME()+MD5Util.lowMd5(password)+sUser.getSALT());
				if(password.equalsIgnoreCase(sUser.getPASSWORD())) {
					StpUtil.login(sUser.getId());
					MagicUser magicUser = new MagicUser(sUser.getId() + "", sUser.getLOGIN_NAME(), StpUtil.getTokenValue());
					userToken.put(StpUtil.getTokenValue(),magicUser);
					return magicUser;
				}
			}
			return null;

	}

	@Override
	public void logout(String token) {
		StpUtil.logout();
	}

	//是否拥有页面按钮的权限
	@Override
	public boolean allowVisit(MagicUser magicUser, MagicHttpServletRequest request, Authorization authorization) {
//		if(magicUser!=null && "admin".equals(magicUser.getUsername())){
//			if(authorization.equals(Authorization.SAVE)){
//				return true;
//			}
//		}
		// Authorization.SAVE 保存
		// Authorization.DELETE 删除
		// Authorization.VIEW 查询
		// Authorization.LOCK 锁定
		// Authorization.UNLOCK 解锁
		// Authorization.DOWNLOAD 导出
		// Authorization.UPLOAD 上传
		// Authorization.PUSH 推送
		return true;
	}

	/**
	 * 是否拥有对该接口的增删改权限
	 * 此方法可以不重写，则走默认的 boolean allowVisit(MagicUser magicUser, MagicHttpServletRequest request, Authorization authorization) 方法
	 */
	@Override
	public boolean allowVisit(MagicUser magicUser, MagicHttpServletRequest request, Authorization authorization, MagicEntity entity) {
		// Authorization.SAVE 保存
		// Authorization.DELETE 删除
		// Authorization.VIEW 查询
		// Authorization.LOCK 锁定
		// Authorization.UNLOCK 解锁
		// 自行写逻辑判断是否拥有如果有，则返回true，反之为false
		return true;
	}
}
